package m202405.d25;

import java.util.*;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/25 16:28
 */
public class Q39 {

    public static void main(String[] args) {
        Q39 q39 = new Q39();
        q39.combinationSum(new int[]{2, 3, 6, 7}, 7);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> rs = new ArrayList<>();
        select(target, candidates, 0, new LinkedList<>(), rs);
        return rs;
    }

    private boolean select(int target, int[] candidates, int start, LinkedList<Integer> list, List<List<Integer>> rs) {
        if (target < 0) {
            return false;
        }
        if (target == 0) {
            rs.add(new ArrayList<>(list));
            return false;
        }
        for (int i = start; i < candidates.length; i++) {
            list.addLast(candidates[i]);
            boolean flag = select(target - candidates[i], candidates, i, list, rs);
            list.removeLast();
            if (!flag) {
                break;
            }
        }
        return true;
    }
}
